<?php
/**************************************
 *
 * @services 图片服务处理
 *
 **************************************/
namespace app\common\services;
use GuzzleHttp\Client;
use think\config;
use think\Env;
use think\Validate;
use JF\FileManager as jfuploads;
use Intervention\Image\ImageManagerStatic as Image;

class ImageServices
{
    /**
     * 按照比例重新计算宽高
     *
     * @param  Image $image 图片文件
     * @param  int $prop 宽高比
     * @param  int $e 0-长边不动 1-短边不动
     * @return Image 图片实例
     */
    public function proportion($image, $prop, $e = 1)
    {
        $rw = $w = $image->width();
        $rh = $h = $image->height();

        if ($w >= $h) {
            $e ? $w = $h*$prop : $h = $w*(1/$prop);
        } else {
            $e ? $h = $w*(1/$prop) : $w = $h*$prop;
        }
        $w = intval($w);
        $h = intval($h);
        // 宽高限制
        $w = $this->limitWorH($w) ? $w : $rw;
        $h = $this->limitWorH($h) ? $h : $rh;
        return [$w, $h];
    }

    /**
     * 图片宽高限制，最大 4096
     *
     * @param  int $v 宽高值
     * @return boolean
     */
    public function limitWorH($v)
    {
        if (!is_int($v) || $v > 4096 || $v <= 0) {
            return false;
        }
        return true;
    }
    /**
     * 图片引用文字描边、文字换行处理
     * @param String $imagefile 图片临时文件
     * @param String $text 写入文本
     * @param String $imgName 图片名
     * @param Int $user_id 用户id
     */
    public function imageWriteText($imagefile, $text, $imgName, $user_id = null)
    {
        Image::configure(array('driver' => 'imagick'));

        $image = Image::make($imagefile);
        $coordinate = ROOT_PATH .'Uploads/home_image.png';

        $image->resize(500, 400);
        $image->insert($coordinate, 'button', 0, 310);
//        $fontFile = __FONTS__. '/static/fonts/pingfang.ttf';
//        $txt = self::autoWrap(24, $fontFile, $text, 560, 1);
        //根据图片高度计算y轴坐标
//        $yCoord = $this->yCoord(mb_strlen($text, 'UTF8'));
//        $image->text($txt, 80, 360, function($font) use($fontFile) {
//            $font->file($fontFile);
//            $font->size(24);
//            $font->color('#fff');
//            $font->align('center');
//            $font->valign('center');
//            $font->strokeColor('9c9c9c');
//            $font->strokeWidth('1');
//        });
        preg_match('/(.*)\/{1}([^\/]*)/i', $imgName, $nameArr);
        $savename = 'article_'. $user_id . $nameArr[2];
        $timeName = date('Ymd', time());
        $path = ROOT_PATH .'Uploads/image/'.$savename;
        $image->save($path);
        return 'Uploads/image/'.$savename;
    }

    /**
     * 图片引用文字描边、文字换行处理
     * @param String $imagefile 图片临时文件
     * @param String $text 写入文本
     * @param String $imgName 图片名
     * @param Int $user_id 用户id
     */
    public function spImageWriteText($imagefile, $text, $imgName, $user_id = null)
    {
        Image::configure(array('driver' => 'imagick'));
        $image = Image::make($imagefile);
        $coordinate = ROOT_PATH .'Uploads/mask_new.png';
        $image->resize(323, 241);
        $image->insert($coordinate);
//        $fontFile = __FONTS__. '/static/fonts/pingfang.ttf';
//        $txt = self::autoWrap(24, $fontFile, $text, 560, 1);
        //根据图片高度计算y轴坐标
//        $yCoord = $this->yCoord(mb_strlen($text, 'UTF8'));
//        $image->text($txt, 160, $yCoord, function($font) use($fontFile) {
//            $font->file($fontFile);
//            $font->size(24);
//            $font->color('#fff');
//            $font->align('center');
//            $font->valign('center');
//            $font->strokeColor('9c9c9c');
//            $font->strokeWidth('1');
//        });
        preg_match('/(.*)\/{1}([^\/]*)/i', $imgName, $nameArr);
        $savename = 'special_'. $user_id . $nameArr[2];
        $timeName = date('Ymd', time());
        $path = ROOT_PATH .'Uploads/image/'.$savename;
        $image->save($path);
        return 'Uploads/image/'.$savename;
    }

    /**
     *  根据字符长度计算Y轴定位坐标
     * @param int $length 字体大小
     */
    public function yCoord($length)
    {
        $yCoord = 120;
        $num = ceil($length/16);
        $num = ($num-1)*20;
        return $yCoord-$num;
    }
    /**
     * 根据预设宽度让文字自动换行
     * @param int $fontsize 字体大小
     * @param string $ttfpath 字体名称
     * @param string $str 字符串
     * @param int $width 预设宽度
     * @param int $fontangle 角度
     * @param string $charset 编码
     * @return string $_string  字符串
     */
    protected static function autoWrap($fontsize, $ttfpath, $str, $width, $fontangle = 0, $charset = 'utf-8')
    {
        $_string = "";
        $_width = 0;
        $temp = self::chararray($str, $charset);
        foreach ($temp[0] as $v) {
            $w = self::charWidth($fontsize, $fontangle, $v, $ttfpath);
            $_width += intval($w);
            if (($_width > $width) && ($v !== "")) {
                $_string .= PHP_EOL;
                $_width = 0;
            }
            $_string .= $v;
        }
        return $_string;
    }
    /**
     * 返回一个字符的数组
     *
     * @param string $str 文字
     * @param string $charset 字符编码
     * @return array $match   返回一个字符的数组
     */
    public static function charArray($str, $charset = "utf-8")
    {
        $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
        $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
        $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
        $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
        preg_match_all($re[$charset], $str, $match);
        return $match;
    }
    /**
     * 返回一个字符串在图片中所占的宽度
     * @param int $fontsize 字体大小
     * @param int $fontangle 角度
     * @param string $ttfpath 字体文件
     * @param string $char 字符
     * @return int $width
     */
    protected static function charWidth($fontsize, $fontangle, $char, $ttfpath)
    {
        $box = @imagettfbbox($fontsize, $fontangle, $ttfpath, $char);
        $width = max($box[2], $box[4]) - min($box[0], $box[6]);
        return $width;
    }

    /*
     *  正方形
     *  @param string $img 图片地址
     */
    public function copeSq($img, $name, $type)
    {
        $image = \think\Image::open($img);
        //正方形比例
        preg_match('/(.*)\/{1}([^\/]*)/i', $name, $nameArr);
        $savename = $type.'_'. $nameArr[2];
        $sq_path = ROOT_PATH .'Uploads/thumb/'.$savename;
        $sqArr = $this->square($img);
        $image->crop($sqArr['w'], $sqArr['h'], $sqArr['p'])->save($sq_path);
    }
    /*
     *  长方形
     */
    public function csJg($img, $name, $type, $pop)
    {
        $image = \think\Image::open($img);
        //长方形
        preg_match('/(.*)\/{1}([^\/]*)/i', $name, $nameArr);
        $savename = $type.'_'. $nameArr[2];
        $idx_path = ROOT_PATH .'Uploads/thumb/'.$savename;
        $idxArr = $this->rect($img, $type, $pop);
        if ($idxArr['t'] == 'w') {
            $image->crop($idxArr['w'], $idxArr['h'], $idxArr['p'])->save($idx_path);
        } elseif($idxArr['t'] == 'h') {
            $image->crop($idxArr['w'], $idxArr['h'], 0, $idxArr['p'])->save($idx_path);
        }
//        echo "<pre>";
//        print_r($idx_path);
//        echo "</pre>";
//        exit();
    }

    /*
     *  正方形比例
     *  @param  String $url
     *  @param  return array
     */
    public function square($url)
    {
        $size = getimagesize($url);
        //宽
        $wh = $size[0];
        //高
        $he = $size[1];
        if ($wh > $he) {
            $posi = ($wh-$he)/2;
            $w = $he;
            $h = $he;
        } elseif ($wh < $he) {
            $posi = ($he-$wh)/2;
            $w = $wh;
            $h = $wh;
        }
        return ['w' => $w, 'h' => $h, 'p' => $posi];
    }
    /*
     *  长方形比例
     *  @param String $url
     *  @param Return array
     */
    public function rect($url, $type, $pop)
    {

        $size = getimagesize($url);
        //宽
        $wh = $size[0];
        //高
        $he = $size[1];
        $b = $wh/$he;
        if ($b < $pop) {
            $h = $wh/$pop;
            $w = $wh;
            $posi = ($he-$h)/2;
            $type = 'h';
        } elseif($b >= $pop) {
            $w = $he*$pop;
            $h = $he;
            $posi = ($wh-$w)/2;
            $type = 'w';
        }
        return ['w' => $w, 'h' => $h, 'p' => $posi , 't' => $type];
    }


    /*
     *  图片压缩
     *  @param string $img 图片地址
     */
    public function thumb($img, $name, $w, $h, $thumbName)
    {
        Image::configure(array('driver' => 'imagick'));
        $image = Image::make($img);
        $image->resize($w, $h);
        preg_match('/(.*)\/{1}([^\/]*)/i', $name, $nameArr);
        $savename = $thumbName.'_'. $nameArr[2];
        $timeName = date('Ymd', time());
        $path = ROOT_PATH .'Uploads/thumb/'.$savename;
        $image->save($path);
//        echo "<pre>";
//        print_r($savename);
//        echo "</pre>";
//        exit();
//        return 'Uploads/thumb/'.$savename;
    }
}